require 'socket'

###############################################################
# Clase ServerNode
# representa a un servidor como un nodo
###############################################################
class ServerNode
	
	def initialize(servername, ip)
		@name = servername
		@ip = ip
		@request = ""
	end
	
	#------------------------------------------------------
	# atributos reader y writer para los datos de instancia
	#------------------------------------------------------
	attr_reader :name, :ip, :request
	attr_writer :name, :ip, :request
	
	#------------------------------------------------------
	# agrega al final de la respuesta el header solicitado
	#------------------------------------------------------
	def addHeader(header_name, header_content)
		@request << "\r\n"
		@request << "#{header_name}: #{header_content}"
	end

	#------------------------------------------------------
	# Set the request to a GET_UVG request
	#------------------------------------------------------	
	def setRequest_to_GET_UVG(server_name)
		@request = "GET_UVG / HTTP/1.1" << "\r\n"
		@request << "Host: #{server_name}/8080" << "\r\n"
		@request << "\r\n\r\n"
	end
	
	#------------------------------------------------------
	# Set the request to a GET request
	#------------------------------------------------------	
	def setRequest_to_GET(path, header_list)
		@request = "GET #{path} HTTP/1.1"
		header_list.each{ |i|
			addHeader(i.split(":",2))
		}
		@request << "\r\n\r\n"
	end
	
	#------------------------------------------------------
	# envía la petición y retorna la respuesta del respectivo
	# servidor
	#------------------------------------------------------
	def sendRequest()
		socket = TCPSocket.open(@ip,8080)  # Connect to server
		socket.print(@request)               # Send request
		response = socket.read              # Read complete response
		return response
	end
	
end
